package app.controllers.admin.movie;

import app.Const;
import app.dtos.MoviePlayDto;
import app.models.DaoKit;
import app.models.movie.Movie;
import com.alibaba.fastjson.JSON;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Page;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.util.*;

/**
 * <p>
 * .
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
public class InfoController extends BasicController {

    public static final String PLAY_TIME_TIME = "play_time_time_";
    public static final String PLAY_TIME_PLACE = "play_time_place_";
    public static final String PLAY_TIME_PRICE = "play_time_price_";


    public void index() {
        setAttr("movieStatus", Const.MOVIE_STATUS_MAP);
        render("index.ftl");
    }

    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        Page<Movie> page = Movie.dao.datatable(criterias);

        renderDataTables(page, criterias);
    }

    public void create() {
        Movie movie = new Movie();
        setAttr("movie", movie);

        setAttr("action", "create");
        setAttr("movieType", Const.MOVIE_TYPES_MAP);
        setAttr("movieStatus", Const.MOVIE_STATUS_MAP);
        render("item.ftl");
    }

    public void edit() {
        long id = getParaToLong(0, 0l);
        Movie movie = Movie.dao.findById(id);

        if (!Strings.isNullOrEmpty(movie.getStr("play_time"))){
            setAttr("playTimes", AppFunc.COMMA_SPLITTER.splitToList(movie.getStr("play_time")));
        }

        String playTimeJson = movie.getStr("play_time");
        if (!Strings.isNullOrEmpty(playTimeJson)) {
            List<MoviePlayDto> playTimeList = JSON.parseArray(playTimeJson, MoviePlayDto.class);
            if (!playTimeList.isEmpty()) {
                setAttr("playTimeList", playTimeList);
            }
        }

        setAttr("movie", movie);
        setAttr("action", "edit");
        setAttr("movieType", Const.MOVIE_TYPES_MAP);
        setAttr("movieStatus", Const.MOVIE_STATUS_MAP);
        render("item.ftl");
    }

    public void save() {
        Movie movie = getModel(Movie.class);
        //String[] strs = getParaValues("play_time");
        String showtimes = getPara("showtimes");
        /*if (strs != null) {
            String s = Const.COMMA_JOINER.join(strs);
            movie.set("play_time", s);
        }*/

        Collection<MoviePlayDto> dtos = parsePlayTime();
        if (dtos != null) {
            String playTime = JSON.toJSONString(dtos);
            movie.set("play_time", playTime);
        }

        if (!Strings.isNullOrEmpty(showtimes)) {
            try {
                DateTime dateTime = DateTime.parse(showtimes, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
                movie.set("showtimes", dateTime.toDate());
            } catch (Exception e) {
                try {
                    DateTime dateTime = DateTime.parse(showtimes, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
                    movie.set("showtimes", dateTime.toDate());
                } catch (Exception e1) {}
            }
        }
        if (DaoKit.isNew(movie)) {
            movie.set("create_time", new Date());
            movie.save();
        } else {
            movie.update();
        }
        redirect("/admin/movie/info");
    }

    private Collection<MoviePlayDto> parsePlayTime() {
        Enumeration<String> names = getParaNames();
        //List<MoviePlayDto> playDtos = Lists.newArrayList();
        TreeMap<String, MoviePlayDto> map = Maps.newTreeMap();
        if (names != null) {
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                if (name.startsWith(PLAY_TIME_TIME)) { //时间
                    String key = name.replace(PLAY_TIME_TIME, "");
                    MoviePlayDto dto = getByKey(map, key);
                    dto.time = getPara(name);
                } else if (name.startsWith(PLAY_TIME_PLACE)) { //影厅
                    String key = name.replace(PLAY_TIME_PLACE, "");
                    MoviePlayDto dto = getByKey(map, key);
                    dto.place = getPara(name);
                } else if (name.startsWith(PLAY_TIME_PRICE)) { //价格
                    String key = name.replace(PLAY_TIME_PRICE, "");
                    MoviePlayDto dto = getByKey(map, key);
                    dto.price = getPara(name);
                }
            }
        }
        return map.values();
    }

    private MoviePlayDto getByKey(TreeMap<String, MoviePlayDto> map, String key) {
        MoviePlayDto dto = map.get(key);
        if (dto == null) {
            dto = new MoviePlayDto();
            map.put(key, dto);
        }
        return dto;
    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("movie.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

}
